package com.xxin.exceptions;

import com.xxin.resp.Result;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 小欣
 * @version 1.0
 * @since 1.8
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
	
	private final Logger log = LogManager.getLogger(GlobalExceptionHandler.class);
	
	
	
	@ExceptionHandler(BusinessException.class)
	public Result<Object> bisException(BusinessException e){
		log.error(e.getMessage());
		return new Result<>(e.getCode(),e.getMessage(),null);
	}
	
	@ExceptionHandler(SystemException.class)
	public Result<Object> sysException(SystemException e){
		log.error(e.getMessage());
		return new Result<>(500,e.getMessage(),null);
	}
	
	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public Result validationExceptionHandler (MethodArgumentNotValidException e) {
		BindingResult exceptions = e.getBindingResult();
// 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
		if (exceptions.hasErrors()) {
			List<ObjectError> errors = exceptions.getAllErrors();
			if (!errors.isEmpty()) {
// 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
				Map prop=new HashMap();
				for (ObjectError error : errors) {
					FieldError fieldError = (FieldError) error;
					prop.put(fieldError.getField(),fieldError.getDefaultMessage());
				}
				return Result.builder().code(500).data(prop).build();
			}
		}
		return Result.error();
	}
	
	@ExceptionHandler(Exception.class)
	public Result<Object> otherException(Exception e){
		e.printStackTrace();
		log.error(e.getMessage());
		return Result.error(e.getMessage());
	}
}
